<?php

namespace app\controller\customer;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;
use think\Response;

/**
 * 客户账号管理
 */
class Account extends BaseController
{
    /**
     * 获取账号列表
     * @return Response
     */
    public function list(): Response
    {
        $params = Request::param();
        $page = intval($params['page'] ?? 1);
        $limit = intval($params['limit'] ?? 20);
        $customerName = $params['customer_name'] ?? '';
        $phone = $params['phone'] ?? '';
        $status = $params['status'] ?? '';

        $query = Db::name('customer_account')
            ->field('id, mobile, customer_id, customer_name, nickname, status, wechat_openid, wechat_unionid, last_login_time, create_time, update_time');

        if ($customerName) {
            $query->where('customer_name', 'like', "%{$customerName}%");
        }

        if ($phone) {
            $query->where('mobile', 'like', "%{$phone}%");
        }

        if ($status !== '') {
            $query->where('status', $status);
        }

        $total = $query->count();
        $list = $query->order('id', 'desc')
            ->page($page, $limit)
            ->select();

        $list = $list ? $list->toArray() : [];

        // 格式化数据
        foreach ($list as &$item) {
            $item['username'] = $item['nickname'] ?: $item['mobile'];
            $item['wechat_bound'] = !empty($item['wechat_openid']);
            $item['create_time'] = $this->formatTime($item['create_time']);
            $item['last_login_time'] = $item['last_login_time'] ? $this->formatTime($item['last_login_time']) : 0;
        }

        return $this->paginate($list, $total, $page, $limit);
    }

    /**
     * 获取账号统计数据
     * @return Response
     */
    public function stats(): Response
    {
        // 总账号数
        $total = Db::name('customer_account')->count();

        // 正常账号（status=1）
        $normal = Db::name('customer_account')->where('status', 1)->count();

        // 冻结账号（status=0）
        $frozen = Db::name('customer_account')->where('status', 0)->count();

        // 禁用账号（status=2）
        $disabled = Db::name('customer_account')->where('status', 2)->count();

        return $this->success([
            'total' => $total,
            'normal' => $normal,
            'frozen' => $frozen,
            'disabled' => $disabled
        ]);
    }

    /**
     * 获取账号详情
     * @return Response
     */
    public function detail(): Response
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $account = Db::name('customer_account')
            ->where('id', $id)
            ->find();

        if (!$account) {
            return $this->error('账号不存在');
        }

        // 格式化数据
        $account['username'] = $account['nickname'] ?: $account['mobile'];
        $account['phone'] = $account['mobile'];
        $account['wechat_bound'] = !empty($account['wechat_openid']);
        $account['create_time'] = $this->formatTime($account['create_time']);
        $account['last_login_time'] = $account['last_login_time'] ? $this->formatTime($account['last_login_time']) : 0;

        return $this->success($account);
    }

    /**
     * 创建账号
     * @return Response
     */
    public function add(): Response
    {
        $params = Request::param();

        // 参数验证
        /** @var \think\Validate $validate */
        $validate = Validate::rule([
            'mobile|手机号' => 'require|mobile',
            'customer_id|客户ID' => 'require|number',
            'customer_name|客户姓名' => 'require'
        ]);

        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }

        // 检查手机号是否已存在
        $exists = Db::name('customer_account')->where('mobile', $params['mobile'])->count();
        if ($exists > 0) {
            return $this->error('手机号已存在');
        }

        // 生成密码和盐
        $salt = $this->randStr(10);
        $password = md5('123456' . $salt); // 默认密码为123456

        $data = [
            'mobile' => $params['mobile'],
            'password' => $password,
            'salt' => $salt,
            'customer_id' => $params['customer_id'],
            'customer_name' => $params['customer_name'],
            'nickname' => $params['nickname'] ?? '',
            'status' => $params['status'] ?? 1,
            'wechat_openid' => $params['wechat_openid'] ?? '',
            'wechat_unionid' => $params['wechat_unionid'] ?? '',
            'create_time' => time(),
            'update_time' => time()
        ];

        $id = Db::name('customer_account')->insertGetId($data);

        if ($id) {
            return $this->success(['id' => $id], '创建成功');
        }

        return $this->error('创建失败');
    }

    /**
     * 更新账号
     * @return Response
     */
    public function edit(): Response
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;

        if (!$id) {
            return $this->error('参数错误');
        }

        // 检查账号是否存在
        $account = Db::name('customer_account')->where('id', $id)->find();
        if (!$account) {
            return $this->error('账号不存在');
        }

        // 检查手机号是否重复
        if ($params['mobile'] && $params['mobile'] !== $account['mobile']) {
            $exists = Db::name('customer_account')
                ->where('mobile', $params['mobile'])
                ->where('id', '<>', $id)
                ->count();
            if ($exists > 0) {
                return $this->error('手机号已存在');
            }
        }

        $data = [
            'mobile' => $params['mobile'] ?? $account['mobile'],
            'customer_name' => $params['customer_name'] ?? $account['customer_name'],
            'nickname' => $params['nickname'] ?? $account['nickname'],
            'status' => $params['status'] ?? $account['status'],
            'wechat_openid' => $params['wechat_openid'] ?? $account['wechat_openid'],
            'wechat_unionid' => $params['wechat_unionid'] ?? $account['wechat_unionid'],
            'update_time' => time()
        ];

        $result = Db::name('customer_account')->where('id', $id)->update($data);

        if ($result !== false) {
            return $this->success([], '更新成功');
        }

        return $this->error('更新失败');
    }

    /**
     * 删除账号
     * @return Response
     */
    public function delete(): Response
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $result = Db::name('customer_account')->where('id', $id)->delete();

        if ($result) {
            return $this->success([], '删除成功');
        }

        return $this->error('删除失败');
    }

    /**
     * 冻结账号
     * @return Response
     */
    public function freeze(): Response
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $result = Db::name('customer_account')->where('id', $id)->update([
            'status' => 0,
            'update_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '冻结成功');
        }

        return $this->error('冻结失败');
    }

    /**
     * 解冻账号
     * @return Response
     */
    public function unfreeze(): Response
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $result = Db::name('customer_account')->where('id', $id)->update([
            'status' => 1,
            'update_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '解冻成功');
        }

        return $this->error('解冻失败');
    }

    /**
     * 绑定微信
     * @return Response
     */
    public function wechat(): Response
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;

        if (!$id) {
            return $this->error('参数错误');
        }

        $result = Db::name('customer_account')->where('id', $id)->update([
            'wechat_openid' => $params['wechat_openid'] ?? '',
            'wechat_unionid' => $params['wechat_unionid'] ?? '',
            'update_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '绑定成功');
        }

        return $this->error('绑定失败');
    }

    /**
     * 格式化时间
     */
    private function formatTime($timestamp)
    {
        if (!$timestamp) return '';
        return date('Y-m-d H:i:s', $timestamp);
    }

    /**
     * 生成随机字符串
     */
    /**
     * 生成随机字符串
     * @param int $length 字符串长度
     * @return string 随机字符串
     */
    private function randStr(int $length = 10): string
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, strlen($chars) - 1)];
        }
        return $str;
    }
}
